package com.yan_jiu_sheng.LeetCodeHot100.AC;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/path-sum-iii/description/?envType=study-plan-v2&envId=top-100-liked
 * 暴力求解 最后一个实例由于部分和超过Integer的最大值而失败 第二次修改为long型成功
 * 通过
 * <p>
 * 更优解：前缀和
 *
 * @author yulongTian
 * @create 2024-06-24 15:45
 */
public class Test48 {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE < Math.pow(10, 9));
        System.out.println(Long.MAX_VALUE);
        System.out.println(1000000000);
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    List<TreeNode> preTravel = new ArrayList<>();
    int ans = 0;

    public int pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return 0;
        }

        preTravel(root);
        for (TreeNode treeNode : preTravel) {
            dfs(treeNode, 0, targetSum);
        }
        return ans;
    }

    private void preTravel(TreeNode root) {
        if (root == null) {
            return;
        }
        //根
        preTravel.add(root);
        //左
        preTravel(root.left);
        //右
        preTravel(root.right);
    }

    private void dfs(TreeNode root, long tempSum, int targetSum) {
        if (root == null) {
            return;
        }

        tempSum += root.val;
        if (tempSum == targetSum) {
            ans++;
        }
        dfs(root.left, tempSum, targetSum);
        dfs(root.right, tempSum, targetSum);
    }


}
